import { useI18n } from '@/hooks/web/useI18n'
import { reactive, UnwrapRef } from 'vue'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { useValidator } from '@/hooks/web/useValidator'
import { ElTag, ElMessage, ElMessageBox, ElButton, ElIcon, ElLink, ElInput } from 'element-plus'

import UploadFile from '@/components/UploadFile/index.vue'
import { Close } from '@element-plus/icons-vue'

const { t } = useI18n()
import { createImageViewer } from '@/components/ImageViewer'
import { SchemaConfig } from '@/api/customer/types'
import { useUserStore } from '@/store/modules/user'
import { Plus } from '@element-plus/icons-vue'
import { useClipboard } from '@vueuse/core'
import { useEnumeratePicker, useEnumerateMultiplePicker } from '@/utils'

const userStore = useUserStore()
const { copy } = useClipboard()

const { required } = useValidator()

interface Option {
  label: string
  value: string | number // 具体取决于你的数据
}

// 通用选项生成函数
const createOptions = (enumObject: { [key: string]: string }): Option[] => {
  return Object.keys(enumObject).map((key) => ({
    label: enumObject[key],
    value: parseInt(key, 10)
  }))
}
const isHidden: Ref<boolean> = ref(true)

export default function useSchema(schemaConfig: any) {
  const statusOption = reactive(createOptions(schemaConfig.fieldEnum?.status || {}))
  const stageOption = reactive(createOptions(schemaConfig.fieldEnum?.stage || {}))
  const custypeOption = reactive(createOptions(schemaConfig.fieldEnum?.custype || {}))
  const cusnatureOption = reactive(createOptions(schemaConfig.fieldEnum?.cusnature || {}))
  const sourceOption = reactive(createOptions(schemaConfig.fieldEnum?.source || {}))
  const isLoginOption = reactive(createOptions(schemaConfig.fieldEnum?.is_login || {}))
  const loginStatusOption = reactive(createOptions(schemaConfig.fieldEnum?.login_status || {}))
  const tripartiteChannelOption = schemaConfig.fieldEnum?.tripartite_channel || {}

  const crudSchemas = reactive<CrudSchema[]>([
    {
      field: 'selection',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        type: 'selection'
      }
    },
    {
      field: 'id',
      label: t('customer.id'),
      align: 'center',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 100,
        slots: {
          default: (data: any) => {
            return (
              <>
                <ElLink
                  type="primary"
                  href={`#/customer/customerList/detail?id=${data.row.id}&source=/customerList?tab=base_info`}
                >
                  {data.row.id}
                </ElLink>
              </>
            )
          }
        }
      }
    },
    {
      field: 'cusname',
      label: t('customer.cusname'),
      form: {
        component: 'Input',
        formItemProps: {
          rules: [required()]
        },
        colProps: {
          span: 24
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 200,
        slots: {
          default: (data: any) => {
            return (
              <>
                <ElLink
                  type="primary"
                  href={`#/customer/customerList/detail?id=${data.row.id}&source=/customerList?tab=base_info`}
                >
                  {data.row.cusname}
                </ElLink>
              </>
            )
          }
        }
      }
    },
    {
      field: 'phone',
      label: t('customer.phone'),
      search: {
        component: 'Input'
      },
      form: {
        component: 'Input'
      },
      table: {
        hidden: schemaConfig.fromPage === 'public',
        headerAlign: 'center',
        align: 'center',
        width: 120
      },
      detail: {
        hidden: schemaConfig.fromPage === 'public'
      }
    },
    {
      field: 'email',
      label: t('customer.email'),
      form: {
        component: 'Input'
      },
      table: {
        hidden: schemaConfig.fromPage === 'public',
        headerAlign: 'center',
        align: 'center',
        width: 200
      },
      detail: {
        hidden: schemaConfig.fromPage === 'public'
      }
    },
    {
      field: 'tripartite_channel_id',
      label: t('customer.tripartite_channel_id'),
      search: {
        component: 'Select',
        componentProps: {
          options: tripartiteChannelOption,
          style: {
            width: '100%'
          }
        }
      },
      form: {
        component: 'Select',
        componentProps: {
          options: tripartiteChannelOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            for (const key in tripartiteChannelOption) {
              if (tripartiteChannelOption[key].value === data.tripartite_channel_id) {
                return tripartiteChannelOption[key].label
              }
            }
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 140,
        slots: {
          default: (data: any) => {
            for (const key in tripartiteChannelOption) {
              if (tripartiteChannelOption[key].value === data.row.tripartite_channel_id) {
                return tripartiteChannelOption[key].label
              }
            }
          }
        }
      }
    },
    {
      field: 'tripartite_account',
      label: t('customer.tripartite_account'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        hidden: schemaConfig.fromPage === 'public',
        headerAlign: 'center',
        align: 'center',
        width: 140
      },
      detail: {
        hidden: schemaConfig.fromPage === 'public',
        slots: {
          default: (data: any) => {
            return (
              <>
                {data.tripartite_account_value && data.tripartite_account_value.includes('http') ? (
                  <div>
                    <ElLink type="primary" href={data.tripartite_account_value} target="_blank">
                      跳转
                    </ElLink>
                    <ElButton
                      link
                      class="m-l-4"
                      type="primary"
                      onClick={() =>
                        (copy(data.tripartite_account_value) as any) &&
                        ElMessage.success('复制成功')
                      }
                    >
                      复制
                    </ElButton>
                  </div>
                ) : (
                  <span>{data.tripartite_account_value}</span>
                )}
              </>
            )
          }
        }
      }
    },
    {
      field: 'nickname',
      label: t('customer.nickname'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 140
      }
    },
    {
      field: 'country_id',
      label: t('customer.country_id'),
      search: {
        hidden: schemaConfig.fromPage !== 'public',
        component: 'Select',
        componentProps: {
          filterable: true,
          options: schemaConfig.countrySelectOptions
        }
      },
      form: {
        formItemProps: {
          rules: [required()]
        },
        component: 'Select',
        componentProps: {
          filterable: true,
          options: schemaConfig.countrySelectOptions
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 140,
        slots: {
          default: (data: any) => {
            return data.row.country
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.country?.cname
          }
        }
      }
    },
    {
      field: 'city',
      label: t('customer.city'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: { hidden: true },
      detail: {
        slots: {
          default: (data: any) => {
            return data.city
          }
        }
      }
    },
    {
      field: 'address',
      label: t('customer.address'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'status',
      label: t('customer.status'),
      search: {
        component: 'Select',
        componentProps: {
          options: statusOption,
          style: {
            width: '100%'
          }
        }
      },
      form: {
        component: 'Select',
        componentProps: {
          options: statusOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(statusOption, data.status)
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 100,
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(statusOption, data.row.status)
          }
        }
      }
    },
    {
      field: 'stage',
      label: t('customer.stage'),
      search: {
        component: 'Select',
        componentProps: {
          options: stageOption,
          style: {
            width: '100%'
          }
        }
      },
      form: {
        component: 'Select',
        componentProps: {
          options: stageOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(stageOption, data.stage)
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 100,
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(stageOption, data.row.stage)
          }
        }
      }
    },
    {
      field: 'tags',
      label: t('customer.tags'),
      search: {
        hidden: true
      },
      form: {
        hidden: false, // 是否隐藏
        componentProps: {
          class: 'invisible-input',
          readonly: true,
          slots: {
            prefix: () => {
              if (
                schemaConfig.tagsWithInputStore?.tagsList &&
                schemaConfig.tagsWithInputStore?.tagsList.length > 0
              ) {
                return schemaConfig.tagsWithInputStore?.tagsList.map((item) => (
                  <ElButton
                    size="small"
                    type="success"
                    plain
                    onClick={() => schemaConfig.tagsWithInputStore?.removeTag(item)}
                  >
                    {item}
                    <ElIcon>
                      <Close />
                    </ElIcon>
                  </ElButton>
                ))
              } else {
                return null
              }
            },
            suffix: () => {
              return (
                <ElButton
                  class="input-button"
                  size="small"
                  type="primary"
                  plain
                  onClick={() => {
                    schemaConfig.tagsWithInputStore?.openDialog()
                    schemaConfig.tagsWithInputStore?.setSchema(schemaConfig.formDialogSchema)
                  }}
                >
                  {t('action.add')}
                </ElButton>
              )
            }
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.tags
              ? data.tags.split(',').map((item) => (
                  <ElTag style="margin-left: 5px;" type={'success'}>
                    {item}
                  </ElTag>
                ))
              : null
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 140,
        slots: {
          default: (data: any) => {
            return data.row.tags
              ? data.row.tags?.split(',').map((item) => (
                  <ElTag style="margin-left: 5px;" type={'success'}>
                    {item}
                  </ElTag>
                ))
              : null
          }
        }
      }
    },
    {
      field: 'loss',
      label: t('customer.loss'),
      search: {
        hidden: true
      },
      form: {
        hidden: false,
        component: 'Input'
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'owner',
      label: t('customer.owner'),
      search: {
        hidden: schemaConfig.fromPage === 'public',
        component: 'Select',
        componentProps: {
          filterable: true,
          options: schemaConfig.operatorOptions,
          style: {
            width: '100%'
          }
        }
      },
      form: {
        formItemProps: {
          rules: [required()]
        },
        component: 'Select',
        componentProps: {
          filterable: true,
          options: schemaConfig.operatorOptions
        },
        value: userStore.getUserInfo?.id
      },
      detail: {
        hidden: schemaConfig.fromPage === 'public',
        slots: {
          default: (data: any) => {
            const operatorOptions = schemaConfig.operatorOptions || []
            return useEnumeratePicker(operatorOptions, data.owner)
          }
        }
      },
      table: {
        hidden: schemaConfig.fromPage === 'public',
        headerAlign: 'center',
        align: 'center',
        width: 120,
        slots: {
          default: (data: any) => {
            return data.row.owner
          }
        }
      }
    },
    {
      field: 'partner',
      label: t('customer.partner'),
      search: {
        hidden: schemaConfig.fromPage === 'public',
        component: 'Select',
        componentProps: {
          filterable: true,
          options: schemaConfig.operatorOptions,
          style: {
            width: '100%'
          }
        }
      },
      form: {
        component: 'Select',
        componentProps: {
          filterable: true,
          multiple: true,
          options: schemaConfig.operatorOptions
        }
      },
      detail: {
        hidden: schemaConfig.fromPage === 'public',
        slots: {
          default: (data: any) => {
            return data.partner_value
          }
        }
      },
      table: {
        hidden: schemaConfig.fromPage === 'public',
        headerAlign: 'center',
        align: 'center',
        width: 120,
        slots: {
          default: (data: any) => {
            // return data.row.partner
            const operatorOptions = schemaConfig.operatorOptions || []
            console.log(123, data.row.partner, operatorOptions)
            return data.row.partner && data.row.partner.length
              ? useEnumerateMultiplePicker(operatorOptions, data.row.partner?.join(','))
              : ''
          }
        }
      }
    },
    {
      field: 'custype',
      label: t('customer.custype'),
      search: {
        hidden: true
      },
      form: {
        formItemProps: {
          rules: [required()]
        },
        component: 'Select',
        componentProps: {
          options: custypeOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(custypeOption, data.custype)
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 100,
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(custypeOption, data.row.custype)
          }
        }
      }
    },
    {
      field: 'cusnature',
      label: t('customer.cusnature'),
      search: {
        component: 'Select',
        componentProps: {
          options: cusnatureOption,
          style: {
            width: '100%'
          }
        }
      },
      form: {
        formItemProps: {
          rules: [required()]
        },
        component: 'Select',
        componentProps: {
          options: cusnatureOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(cusnatureOption, data.cusnature)
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 100,
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(cusnatureOption, data.row.cusnature)
          }
        }
      }
    },
    {
      field: 'source',
      label: t('customer.source'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        value: 6,
        componentProps: {
          options: sourceOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(sourceOption, data.source)
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 100,
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(sourceOption, data.row.source)
          }
        }
      }
    },
    {
      field: 'company_name',
      label: t('customer.company_name'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input'
      },
      detail: {
        slots: {
          default: (data: any) => {
            return <span>{data.company_name}</span>
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 120,
        slots: {
          default: (data: any) => {
            return <span>{data.row.company_name}</span>
          }
        }
      }
    },
    {
      field: 'att_path',
      label: t('customer.att_path'),
      search: {
        hidden: true
      },
      form: {
        formItemProps: {
          slots: {
            default: (data: any) => (
              <div class="flex flex-col">
                <UploadFile
                  url={'/common/uploadFile'}
                  fileType={['png', 'jpg', 'jpeg', 'doc', 'docx', 'xls', 'xlsx', 'pdf']}
                  params={{ directory: 2 }}
                  limit={9}
                  // isSlot={true}
                  listType={'text'}
                  fileListMap={data.att_path_urls}
                  showFileList={true}
                  // @ts-ignore
                  uploadSuccessRes={({ fileList }: Record<string, any>) => {
                    const ids = fileList.map((item: any) =>
                      item.response ? item.response.data.id : item.id
                    )
                    schemaConfig.setValues({ att_path: ids })
                  }}
                  // @ts-ignore
                  handleRemoveFile={(fileList: Record<string, any>) => {
                    const ids = fileList.map((item: any) =>
                      item.response ? item.response.data.id : item.id
                    )
                    schemaConfig.setValues({ ...data, att_path: ids })
                  }}
                  downloadFile={(url: string) => {
                    if (!url) return
                    if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url))
                      return createImageViewer({
                        urlList: [url]
                      })
                    window.open(url)
                  }}
                  uploadFileButtonName="上传附件"
                >
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                </UploadFile>
                <div class="m-t-3 text-xs text-gray-800">最多上传 9 个文件</div>
              </div>
            )
          }
        }
      },
      table: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return (
              <UploadFile
                url={'/common/uploadFile'}
                fileType={['png', 'jpg', 'jpeg', 'doc', 'docx', 'xls', 'xlsx', 'pdf']}
                params={{ directory: 2 }}
                limit={9}
                disabled={true}
                uploadDisabled={true}
                isSlot={true}
                listType={'text'}
                fileListMap={data.att_path_urls}
                showFileList={true}
                downloadFile={(url: string) => {
                  if (!url) return
                  if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url))
                    return createImageViewer({
                      urlList: [url]
                    })
                  window.open(url)
                }}
              />
            )
          }
        }
      }
    },
    {
      field: 'remark',
      label: t('customer.remark'),
      search: {
        component: 'Input'
      },
      form: {
        component: 'Input',
        componentProps: {
          type: 'textarea'
        }
      },
      table: {
        width: 150,
        align: 'center',
        headerAlign: 'center'
      }
    },
    {
      field: 'is_del',
      label: t('customer.is_del'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'is_login',
      label: t('customer.is_login'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        componentProps: {
          options: isLoginOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(isLoginOption, data.is_login)
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 100,
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(isLoginOption, data.row.is_login)
          }
        }
      }
    },
    {
      field: 'login_num',
      label: t('customer.login_num'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 100
      }
    },
    {
      field: 'last_login_time',
      label: t('customer.last_login_time'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        minWidth: 130
      }
    },
    {
      field: 'last_ip',
      label: t('customer.last_ip'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 120
      }
    },
    {
      field: 'login_status',
      label: t('customer.login_status'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        componentProps: {
          options: loginStatusOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(loginStatusOption, data.login_status)
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 120,
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(loginStatusOption, data.row.login_status)
          }
        }
      }
    },
    {
      field: 'is_advance',
      label: t('customer.is_advance'),
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        componentProps: {
          options: [
            { label: '否', value: '0' },
            { label: '是', value: '1' }
          ]
        },
        value: '0' // 设置默认选中值为 '0'
      },
      table: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.is_advance_text
          }
        }
      }
    },
    {
      field: 'create_time',
      label: t('customer.create_time'),
      search: {
        component: 'DatePicker',
        componentProps: {
          type: 'daterange',
          valueFormat: 'YYYY-MM-DD',
          unlinkPanels: true,
          rangeSeparator: '-'
        }
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        minWidth: 130
      }
    },
    {
      field: 'creator',
      label: t('customer.creator'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            const operatorOptions = schemaConfig.operatorOptions || []
            return useEnumeratePicker(operatorOptions, data.creator)
          }
        }
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'update_time',
      label: t('customer.update_time'),
      search: {
        component: 'DatePicker',
        componentProps: {
          type: 'daterange',
          valueFormat: 'YYYY-MM-DD',
          unlinkPanels: true,
          rangeSeparator: '-'
        }
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        minWidth: 130
      }
    },
    {
      field: 'updater',
      label: t('customer.updater'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            const operatorOptions = schemaConfig.operatorOptions || []
            return useEnumeratePicker(operatorOptions, data.updater)
          }
        }
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'action',
      width: (schemaConfig.actionButtonsTemplate?.length || 3) * 60 + 20 + 'px',
      label: t('tableDemo.action'),
      fixed: 'right',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        hidden:
          !schemaConfig.actionButtonsTemplate || schemaConfig.actionButtonsTemplate.length === 0,
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return schemaConfig.actionButtonsTemplate?.template(data) ?? null
          }
        }
      }
    }
  ])

  return {
    crudSchemas
  }
}
